package com.huan.rss.writer;

import com.huan.rss.bean.CommonInformationItem;
import com.huan.rss.buffer.NewBuffer;
import com.huan.rss.dao.ProjectProperties;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 从缓存中取数据，写到磁盘（mogodb,数据库）
 */
public class NewsWriterTask implements Runnable{

    private Logger logger = Logger.getLogger(NewsWriterTask.class);
    private String name;//rss源名称，用来做磁盘文件的文件名
    private NewBuffer buffer;//缓存

    public NewsWriterTask(String name,NewBuffer buffer){
        this.name = name;
        this.buffer = buffer;
    }
    public NewsWriterTask(NewBuffer buffer) {
        this.buffer = buffer;
        this.name = "未知新闻源";
    }
    @Override
    public void run() {
        boolean flag = false;
        while(!flag && !Thread.currentThread().isInterrupted()){
            CommonInformationItem item = null;
            try {
                item = buffer.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (item == null){
                continue;
            }
            //保存到数据库/磁盘
            //将数据写到磁盘
            Path p = Paths.get(ProjectProperties.getInstance().getProperty("file.path") +item.getFileName());
            //流：                      创建一个缓冲字符流（因为可以一行一行的写数据）        CREATE：如果文件不存在，则创建一个新的文件，每次创建一个新文件
            try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.CREATE)){
                writer.write(item.toString());
                writer.flush();
            }catch (IOException e){
                logger.error("写入文件失败",e);
            }
        }
    }
}
